package com.cosmoplat.gfqd.utils;

import com.cosmoplat.gfqd.config.BootStrapConfig;
import com.cosmoplat.gfqd.constants.Constants;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.models.Project;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.cosmoplat.gfqd.config.ConfigLoader.loadConfig;

public class CloneGitLab {
    private static String GITLAB_URL; // GitLab 的 URL
    private static String ACCESS_TOKEN; // GitLab 的访问令牌
    private static String GITLAB_ACCOUNT; // GitLab 的账号
    private static String GROUP_ID; // 目标 Group 的 ID
    private static List<Long> PROJECT_IDS; // 目标 PROJECT 的 id
    private static List<Long> EXCLUDE_PROJECT_IDS; // 不需要clone PROJECT 的 id

    public static void clone(BootStrapConfig config,String branch) {

        if (config != null) {
            System.out.println("Loaded bootstrap: " + config);
            // Access config values
            GITLAB_URL = config.getGitlab().getUrl();
            ACCESS_TOKEN = config.getGitlab().getAccessToken();
            GITLAB_ACCOUNT = config.getGitlab().getAccount();
            GROUP_ID = config.getGitlab().getGroupId();
            PROJECT_IDS = config.getGitlab().getProjectIds();
            EXCLUDE_PROJECT_IDS = config.getGitlab().getExcludeProjectIds();
        }

        // 清空目标目录
        ClearDirectory.clear(Constants.GITLAB_PROJECTS);

        // 克隆项目
        cloneGitProject(branch);

    }


    private static void cloneGitProject(String branch) {
        GitLabApi gitLabApi = new GitLabApi(GITLAB_URL, ACCESS_TOKEN);
        List<ProjectStatus> projectStatuses = new ArrayList<>(); // 用于记录每个项目的克隆状态

        try {
            List<Project> projects;
            // 获取 Group 下的所有项目
            // 如果不配置groupId,按照配置的projectPath路径去克隆
            if (Objects.nonNull(GROUP_ID)) {
                projects = gitLabApi.getGroupApi().getProjects(GROUP_ID);
            } else {
                projects = PROJECT_IDS.stream().map(item -> {
                    try {
                        Project project = gitLabApi.getProjectApi().getProject(item);
                        return project;
                    } catch (GitLabApiException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
            }
            //去掉不想clone的project
            if (Objects.nonNull(EXCLUDE_PROJECT_IDS) && EXCLUDE_PROJECT_IDS.size() > 0) {
                projects = projects.stream().filter(project -> !EXCLUDE_PROJECT_IDS.contains(project.getId()))
                        .collect(Collectors.toList());
            }
            // 批量执行克隆命令
            for (Project project : projects) {
                String projectName = project.getName();
                String projectGitUrl = project.getHttpUrlToRepo();
                File projectDir = new File( Constants.GITLAB_PROJECTS, projectName);

                System.out.println("Cloning project: " + projectName + " from " + projectGitUrl);

                boolean success = cloneProjectProcess(projectGitUrl, branch, projectDir);
                projectStatuses.add(new ProjectStatus(projectName, success));
            }

        } catch (
                GitLabApiException e) {
            System.err.println("Error accessing GitLab API: " + e.getMessage());
        }

        // 打印项目克隆结果
        printCloneSummary(projectStatuses);

    }


    // 执行克隆命令
    private static boolean cloneProjectProcess(String gitUrl, String branch, File directory) {
        if (directory.exists()) {
            System.out.println("Directory " + directory.getName() + " already exists, skipping...");
            return true;
        }

        try {
            Git.cloneRepository()
                    .setURI(gitUrl)
                    .setBranch(branch)
                    .setDirectory(directory)
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GITLAB_ACCOUNT, ACCESS_TOKEN)) // 使用用户名和访问令牌认证
                    .call();
            System.out.println("Cloned " + gitUrl + " to " + directory.getPath());
            return true;
        } catch (GitAPIException e) {
            System.err.println("Failed to clone " + gitUrl + ": " + e.getMessage());
            return false;
        }
    }

    // 打印项目克隆结果
    private static void printCloneSummary(List<ProjectStatus> projectStatuses) {
        System.out.println("\n--- Clone Summary ---");
        int successCount = 0;
        for (ProjectStatus status : projectStatuses) {
            String result = status.isSuccess() ? "Success" : "Failed";
            System.out.println("Project: " + status.getProjectName() + " - " + result);
            if (status.isSuccess()) {
                successCount++;
            }
        }
        System.out.println("Total projects: " + projectStatuses.size());
        System.out.println("Successfully cloned: " + successCount);
        System.out.println("Failed to clone: " + (projectStatuses.size() - successCount));
    }


}